package edu.ucla.cs.cs144;

import java.io.*;
import java.text.*;
import java.util.*;

import java.io.IOException;
import java.net.HttpURLConnection;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URI;


public class ProxyServlet extends HttpServlet implements Servlet {
       
    public ProxyServlet() {}

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
	HttpURLConnection connection = null;
	OutputStreamWriter wr = null;
	BufferedReader rd  = null;
	StringBuilder sb = null;
	String line = null;
	URL serverAddress = null;
	URI myURI = null;

	try 
	{
		HttpSession session = request.getSession(true);	
		String q = request.getParameter("q");
		
		myURI = new URI("http", "google.com", "/complete/search", "output=toolbar&q=" + q, null);
		
		serverAddress = myURI.toURL();
		//set up out communications stuff

		//Set up the initial connection
		connection = (HttpURLConnection)serverAddress.openConnection();
		connection.setRequestMethod("GET");
		connection.setDoOutput(true);
		connection.setReadTimeout(10000);
		    
		connection.connect();

		//read the result from the server
		rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		sb = new StringBuilder();

		while ((line = rd.readLine()) != null)
		{
			sb.append(line + '\n');
		}

		PrintWriter out = response.getWriter();
		out.println(sb.toString()); // contains suggest XML data
		response.setContentType("text/xml");
	} 
	catch (MalformedURLException e) 
	{
		e.printStackTrace();
	} 
	catch (ProtocolException e) 
	{
		e.printStackTrace();
	} 
	catch (IOException e) 
	{
		e.printStackTrace();
	}
	catch (URISyntaxException e)
	{
		e.printStackTrace();
	}
	finally
	{
		//close the connection, set all objects to null
		connection.disconnect();
		rd = null;
		sb = null;
		wr = null;
		connection = null;
	}
    }
}
